package com.wmx.blockingQueue;

import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyTask {
    private volatile Boolean flg = true;
    private AtomicInteger atomicInteger = new AtomicInteger();
    private BlockingQueue blockingQueue;

    public MyTask(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void myProd() throws InterruptedException {
        boolean result;
        while (flg) {
            TimeUnit.SECONDS.sleep(2);
            int data = atomicInteger.incrementAndGet();
            result = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if (result) {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列data：" + data + "\t 成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列data：" + data + "\t 成功");
            }
        }
    }

    public void myConsumer() throws InterruptedException {
        Object poll = null;
        while (flg) {
            poll = blockingQueue.poll(2, TimeUnit.SECONDS);
            if(Objects.isNull(poll)){
                System.out.println(Thread.currentThread().getName() + "\t 超过两秒没收到消息");
                System.out.println("");
                System.out.println("");
                System.out.println("");
                continue;
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费队列value：" + poll + "成功");
        }
    }

    public void stop(){
        flg = false;
    }


}
